<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends MY_Controller {
	public function __construct(){

		// $this->need_login=true;
		parent::__construct();

	}
	public function adduser()
	{
		$this->load->view('admin/user.html');
	}

	public function useradd(){
		$this->load->database();
	 	$this->load->model('User_model','user');
		$key =  date('YmdHis').rand(1000,9999);
		$key = md5($key);
		$data["key"] = $key;
		if(!empty($_POST)){
			$username = trim( $_POST['username']);
			$level = $_POST['level'];
			$password = md5(trim($_POST['password']));
			$key=$_POST['key'];
			$res = $this->user->adduser($username,$password,$level,$key);
			if($res=='1'){
				echo json_encode(array('code'=>0,'msg'=>'添加用户成功'));
				exit;
			}else if($res=='110'){
				echo json_encode(array('code'=>110,'msg'=>'用户名已存在'));
				exit;
			}else{
				echo json_encode(array('code'=>5000,'msg'=>'添加用失败'));
				exit;
			}
		}
		$this->load->view('user/useradd.html',$data);
	}

	public function changepwd(){
		$this->load->database();

		if (!empty($_POST)) {
			$username = $_COOKIE['mercode'];
			$newpass = md5($_POST['newpass']);
			$newkey = $_POST['newkey'];
			if($newkey!=''&& strlen($newkey)==32){
				$sql = "UPDATE file_user SET password = '$newpass',key = '$newkey' WHERE username='$username'"; 	  		
	  	  		$query = $this->db->query($sql);
	  	  		$row = $query->row();
	  	  		if($row!=''){
	  	  			echo json_encode(array('code'=>'0','msg'=>'修改成功'));
	  	  			exit;
	  	  		}else{
	  	  			echo json_encode(array('code'=>'30006','msg'=>'密钥有问题'));
	  	  			exit;
	  	  		}
			}else{
				$sql = "UPDATE file_user SET password = '$newpass' WHERE username='$username'"; 
				
	  	  		$query = $this->db->query($sql);
	  	  		
	  	  		if($query==true){
	  	  			echo json_encode(array('code'=>'0','msg'=>'修改成功'));
	  	  			exit;
	  	  		}else{
	  	  			echo json_encode(array('code'=>'30006','msg'=>'修改失败'));
	  	  			exit;
	  	  		}
			}

			
		}
		$this->load->view('user/changepwd.html');
	}
	public function login(){
		$this->load->helper('func');
		$this->load->helper('captcha');
		$this->load->database();


		if(!empty($_POST)){
			
			$username = $_POST['username'];
			$password = md5($_POST['password']);
			$sql = "SELECT * FROM file_user WHERE  username = '$username' and password='$password' ";
			
			 $query = $this->db->query($sql);
			 $logintime = date('Y-m-d H:i:s');
			 
        	 $row = $query->row();
        	 $sql = "UPDATE file_user SET logintime = '$logintime' WHERE username='$username'"; 
				
	  	  		$res = $this->db->query($sql);	 

        	 if($row->id!=''&&$res=='1'){
        	 	echo json_encode(array('code'=>'0','msg'=>'登录成功'));
        	 	exit;
        	 }else{
        	  echo	json_exit("30005","登录失败");
        	 }
		}

		$this->load->view('user/login.html');
	}

	

	/**
	*更改密钥
	*/
	 public function changekey(){
	 	$this->load->helper('func'); 	
	 	$this->load->database();
	 	$this->load->model('User_model','user');
	 	$username = $_COOKIE['mercode'];
	 	
	 	$data = $this->user->getKey($username);//mercode商户号就是用户名
	 	$res['key'] =  $data[0]->key;
	 	
	 	if(!empty($_POST['password'])){
	 		$check = $this->user->checkPass($username,$_POST['password']); 
	 		$id = $check[0]->id;
	 		if(empty($check)){
	 			echo json_encode(array('code'=>'50000','msg'=>'密码不正确'));
	 			exit();
	 		}
	 		$newkey = md5(date('YmdHis').mt_rand(10000,99999));	
	 		$row = $this->user->updateKey($id,$newkey);
	 		if($row){
	 			echo json_encode(array('code'=>0,'msg'=>'密钥重新生成功','key'=>$newkey));
	 			exit();
	 		}
	 	}

      $this->load->view('user/userkey.html',$res);
  }
  /**
*获取绘图数据
*/
  public function charts(){
  		$this->load->helper('func'); 	
	 	$this->load->database();
		$mercode=$_COOKIE['mercode'];
		$this->load->model('User_model','user');
		$logpath='/data/log/file_service/';
		if(!empty($_POST)){			
			if(!empty($_POST['day'])){
				$res = file_get_contents($logpath.$_POST['day'].'_'.$mercode.".json");
				$daycount = dayCount($_POST['day'],$mercode);
				$count["daycount"]= getSize($daycount);
			}		
		
			$count["str"] =$res;

			echo json_encode(array("code"=>"0","msg"=>"获取成功","info"=>$count));
			exit();
		}else{
			$dayFlowTotal = dayFlow($mercode);//从nginx日志文件生成当天下载数据并存到json文件
			$filename=date("Y-m-d").'_'.$mercode.".json";		//默认获取当日数据
			 $res = file_get_contents($logpath.$filename);

			$daytotal=dayCount(date("Y-m-d"),$mercode);//每日总流量
			
			$data['str']=$res;
			
			$data['daytotal']=getRealSize($dayFlowTotal);//当日总流量
			
			
			
		}
		
  		$this->load->view('user/daycharts.html',$data);
  }
  /**
  *校验密码
  */
  public function cheakPass(){
  	$this->load->database();
  	$this->load->model('User_model','user');
  	$username = $_COOKIE['mercode'];
  	if(!empty($_POST['password'])){
  		$check = $this->user->checkPass($username,$_POST['password']); 
		$id = $check[0]->id;
		if(empty($check)){
	 		echo json_encode(array('code'=>'50000','msg'=>'密码不正确'));
	 		exit();
	 	}else{
	 		echo json_encode(array('code'=>0,'msg'=>'密码正确'));
	 		exit();
	 	}
  	}
  	
  }
/**
*下载密钥
*/
  public function downLoadkey(){
  		$this->load->database();
  		$this->load->model('User_model','user');
  		$username = $_COOKIE['mercode'];
  				if(!empty($username)){
  				$query = $this->user->getKey($username);		
  				$key =  $query[0]->key;
  				if(!empty($key)){
  					$filename = date('YmdHis').'_key.txt';
				  	$root_path = FCPATH.'uploads/';
				  	$file_path=$root_path.$filename;
				  	$key='key:'.$key;
			  		file_put_contents($file_path, $key);
  				  if(file_exists($file_path)){
	                    header("Content-Type: application/force-download");
	                    header("Content-Disposition: attachment; filename=".$filename);
	                    header("Accept-length:".filesize($file_path));
	                    readfile($file_path);
                   		 exit;  
		               }else{
		                    echo json_exit(40001,'文件不存在'); 
		                }
  					}
  				}						  	
  }
  /**
  *获取指定时间的数据
  */
  public function selectData(){
	  $this->load->helper('func'); 
	  $this->load->database();
      $this->load->model('User_model','user');
	  $mercode=$_COOKIE['mercode'];
	 
		if(!empty($_POST)){
			$starttime = $_POST['starttime'];
			$endtime = $_POST['endtime'];
			$count=array();
			$data = $this->user->getDaydata($starttime,$endtime,$mercode);
				end($data);
				$key_last = key($data);
				foreach($data as $key => $value){	
					$x.=date('Ymd',strtotime($value->date)).',';	
					$y.= $value->dayflow.',';
					
					if($key_last==$key){
						
						$res .= '['.date('Ymd',strtotime($value->date)).','.$value->dayflow.']'.PHP_EOL;
						$total+=$value->dayflow;
					}else{
						$res.='['.date('Ymd',strtotime($value->date)).','.$value->dayflow.'],'.PHP_EOL;
						$total+=$value->dayflow;
					}
				}	
					$x='['.trim($x,',').']';
					$y='['.trim($y,',').']';
					$count['x']=$x;
					$count['y']=$y;
					$total += $value->dayflow;
					echo json_encode(array('code'=>0,'data'=>$count,'total'=>getSize($total)));
				//echo json_encode(array('code'=>'0','msg'=>'','data'=>$res,));
				exit;
			
			
		}
	}
	/**
	*获取本月数据
	*/
	public function mouthData(){
	  $this->load->helper('func'); 
	  $this->load->database();
      $this->load->model('User_model','user');
	  $mercode=$_COOKIE['mercode'];
	  $count =array();  
		  $mouthdata=$this->user->getTheday($mercode);
		  //var_dump($mouthdata);die;
				foreach($mouthdata as $key=>$val){
													
						$y.=$val->dayflow.',';	
						$x.=date('Ymd',strtotime($val->date.'')).',';
						$total += $val->dayflow;
					
				}
				
				$x='['.trim($x,',').']';
				$y='['.trim($y,',').']';		
				$count["x"]=$x;
				$count['y']=$y;
				$count['total']=getSize($total) ;			
	  
	  	$this->load->view('user/mouthcharts.html',$count);
	  
	}
	


}